package com.tank.model;

import com.tank.control.ColliderChain;
import com.tank.control.DirectionEnum;
import com.tank.control.TankWindowsKeyListener;
import com.tank.entrity.*;
import com.tank.window.GameApplicationWindows;
import java.awt.*;
import java.util.*;
import java.util.List;

public class GameModel {


    /** 我方坦克 */
    private final GameObject mainTank;
    /** 敌方坦克 */
    private final List<GameObject> gameObjects;

    private final ColliderChain colliderChain;

    public final static GameModel INSTANCE = new GameModel();

    public final Map<String, GameObject> map;

    private GameModel() {
        this.colliderChain = new ColliderChain();
        this.gameObjects = new ArrayList<>();
        Random random = new Random();
        mainTank = new Tank(random.nextInt(GameApplicationWindows.WINDOWS_WIDTH), random.nextInt(GameApplicationWindows.WINDOWS_HEIGHT), DirectionEnum.DOWN, GroupType.GOOD, false, null, UUID.randomUUID());
        initGameWallObject();
        this.map = new HashMap<>();
        GameApplicationWindows.getInstance().addKeyListener(new TankWindowsKeyListener((Tank) mainTank));
    }

    public GameObject getMainTank() {
        return mainTank;
    }

    public static GameModel getInstance() {
        return INSTANCE;
    }

    public GameModel addTank(Tank tank) {
        this.map.put(String.valueOf(tank.getUuid()), tank);
        return this;
    }

    public void addObject(GameObject gameObject) {
        this.gameObjects.add(gameObject);
    }

    public void initGameWallObject() {
        addObject(new Wall(150, 150, 200, 50));
        addObject(new Wall(550, 150, 200, 50));
        addObject(new Wall(300, 300, 50, 200));
        addObject(new Wall(550, 300, 50, 200));
    }

    public int size() {
        return this.gameObjects.size();
    }

    public void removeObject(GameObject gameObject) {
        this.gameObjects.remove(gameObject);
    }

    public void paint(final Graphics graphics) {
        mainTank.paint(graphics);
        map.values().stream().forEach(item -> item.paint(graphics));
        for (int i = 0; i < gameObjects.size(); i++) {
            gameObjects.get(i).paint(graphics);
        }
        objectCollision();
    }

    /**
     * 物体碰撞检测
     */
    public void objectCollision() {
        for (int i = 0; i < gameObjects.size(); i++) {
            for (int j = i + 1; j < gameObjects.size(); j++) {
                if (colliderChain.collide(gameObjects.get(i), gameObjects.get(j))) {
                    return;
                }
            }
        }
    }

    public Object findTankByUUID(UUID id) {
        return this.map.get(String.valueOf(id));
    }

}
